package com.qf.tenant.manager.service.impl;

import cn.hutool.db.DaoTemplate;
import com.qf.common.bean.R;
import com.qf.common.dto.DeviceDto;
import com.qf.common.model.QfDevice;
import com.qf.common.model.QfDeviceTopic;
import com.qf.common.utils.IdWorker;
import com.qf.tenant.manager.feign.DeviceFeign;
import com.qf.tenant.manager.feign.TopicFeign;
import com.qf.tenant.manager.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * @author 千锋健哥
 */
@Service
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private DeviceFeign deviceFeign;

    @Autowired
    private TopicFeign topicFeign;

    @Override
    public R<QfDevice> add(DeviceDto dto) {
        //1. 生成设备key, 规则:  device_雪花算法生成唯一id
        String deviceKey = "device_" + new IdWorker().nextId();
        dto.setDeviceKey(deviceKey);

        //2. 生成设备的秘钥, 随机字符串作为设备秘钥
        dto.setDeviceSecret(UUID.randomUUID().toString().replace("-", ""));

        //3. 设置设备的创建时间, 更新时间, 删除状态, 激活状态
        dto.setCreateTime(new Date());
        dto.setUpdateTime(new Date());
        dto.setDeleted(false);
        //默认设备未激活
        dto.setState(false);

        //4. 保存设备信息
        QfDevice qfDevice = new QfDevice();
        dto.convertDtoToDo(qfDevice);
        R<QfDevice> deviceResult = deviceFeign.add(qfDevice);

        //5. 生成Topic通道数据, 上报传感器数据通道
        QfDeviceTopic deviceTopic = new QfDeviceTopic();
        //   /qfjava/device/data/设备key
        deviceTopic.setTopic("/qfjava/device/data/" + deviceKey);
        deviceTopic.setCreateTime(new Date());
        deviceTopic.setUpdateTime(new Date());
        deviceTopic.setDeleted(false);
        deviceTopic.setDeviceKey(deviceKey);
        R<QfDeviceTopic> r1 = topicFeign.add(deviceTopic);

        //6. 生成Topic通道数据, 平台下发指令通道
        deviceTopic.setTopic("/qfjava/device/ctrl/" + deviceKey);
        R<QfDeviceTopic> r2 = topicFeign.add(deviceTopic);
        return deviceResult;
    }

}
